from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

import datetime
import os
import cgi
from model import *

_DEBUG =True
HTTP_DOMAIN_ADDRESS = "http://" + os.environ['HTTP_HOST']
RSS_CACHE_TIME = 3600

class BasePage(webapp.RequestHandler):
  """
  TODO: Rewrite base page.
  1.Use Cache facility
  """

  def __init__(self, *args, **kwds):
    webapp.RequestHandler.__init__(self, *args, **kwds)

    self.basicset = BasicSet.get_or_insert(key_name='basicset')
    if self.basicset.initial == True:
      self.basicset.articalchanged = True
      self.basicset.initial = False
      self.basicset.put()


    self.recentarticals = db.GqlQuery("SELECT * FROM Articals ORDER BY postdate DESC LIMIT 5")
    self.recentarticals =self.generate_cache('recentarticals.html')

  def generate(self, template_name, template_values={}):
    values = {
      'recentarticals':self.recentarticals,
      'editormode':False,
      'adminmode':True if users.is_current_user_admin() else False,
      'logininfo':self.logininfo(),
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))

  def logininfo(self):
      user = users.get_current_user()
      if user:
          greeting = ("<a>%s|</a><a href=\"%s\">Logout</a>" %(user.nickname(),users.create_logout_url(self.request.uri)))
      else:
          greeting = ("<a href=\"%s\">Login</a>" %
          users.create_login_url(self.request.uri))

      return greeting

  def generate_cache(self, template_name, template_values={}):
    values = {
      'recentarticals':self.recentarticals,
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    content = template.render(path, values, debug=_DEBUG)
#    if not memcache.set(template_name,content,0):
#      raise "Cache Error"
    return content

class Navigate(webapp.RequestHandler):
  def get(self):
    self.pastarticals = db.GqlQuery("SELECT * FROM Articals ORDER BY postdate DESC LIMIT 5")
    self.archivelist = db.GqlQuery("SELECT * FROM Archivelist ORDER BY month DESC")
    values={
            'pastarticals':self.pastarticals,
            'archivelist':self.archivelist,
            }
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', 'navigate.html'))
    content = template.render(path, values, debug=_DEBUG)
    self.response.out.write(content)


class ArchiveView(BasePage):
  '''
  Precent The requested month's artical in BasePage
  Howto: Update BasePage's recentartical
  '''
  def get(self,year,month):
    target_month = Archivelist.keygen(year, month)
    self.recentarticals = Archivelist.get_by_key_name(key_names = target_month).this_month_artical.order('-postdate')
    self.recentarticals = self.generate_cache('recentarticals.html')
    self.generate('base.html',{'recentarticals':self.recentarticals,})


class SingleArtical(BasePage):
  '''
  Precent the requested artical in BasePage
      '/([12]\d\d\d)/(\d|[01]\d)/([\w]+)' : '/2008/5/Title'
  Hoto: Update BasePage's recentartical
  '''
  def get(self,year,month,key):
    self.recentarticals = Articals.get(db.Key(encoded=key))
    self.recentarticals = self.generate_cache('recentarticals.html')
    self.generate('base.html',{'recentarticals':self.recentarticals,})

class Jeditable(webapp.RequestHandler):
  '''
  TODO: Make the inline editor can store content to User
  Identify the content type by request's id arg.
  '''
  def post(self):
    value = self.request.get('value')
    requestid = self.request.get('id')
    value_display = cgi.escape(value)
    self.response.out.write(value_display)

class RSSHandler(webapp.RequestHandler):
  '''
  Handler of RSS feed, have cache ability

  memcache_key:
      update_rss  as state
      rsscache   as container

  Global:
      RSS_CACHE_TIME

  '''
  def get(self):
    if memcache.get("update_rss"):
        tmp = self.render_rss
        memcache.set("rsscache",tmp,RSS_CACHE_TIME)
        memcache.set("update_rss",False)
        self.response.out.write(tmp)
    else:
        tmp = memcache.get("rsscache")
        if not tmp:
            tmp = self.render_rss
            memcache.set("rsscache",tmp,RSS_CACHE_TIME)
        self.response.out.write(tmp)

  @property
  def render_rss(self):
    articals = db.GqlQuery("SELECT * FROM Articals ORDER BY postdate DESC ")

    try:
      builddate = memcache.get("time_of_new_artical_add")
    except:
      builddate = datetime.datetime.utcnow() #Avoid Server DownTime Error

    template_path = "templates/rss.xml"
    template_dict={
                   'articals':articals,
                   'lastbuilddate':builddate,
                   'hosturl':HTTP_DOMAIN_ADDRESS ,
                  }
    return template.render(template_path, template_dict,debug=True)

